import axios from 'axios'
import Vue from 'vue'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import store from '@/store/modules/user'
import { getToken } from '@/utils/auth'

const DEFAULT_ERROR_MES="服务器繁忙"
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

//  TODO request interceptor 请求拦截器
service.interceptors.request.use(
  config => {
    // 判断vuex是否有token
    if (store.getters.token) {
      //当前必须有token才会携带token
      //
      //TODO 如果有token 从cookie中获取到token,将其添加到当前请求的请求头中
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// TODO response interceptor 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // TODO response.data={code:"",msg:"",data:{}}
    //当改成200 时 mock里面的code:20000也要替换层code:200
    if (res.code !== 200) {
      Message({
        message: res.msg || DEFAULT_ERROR_MES,
        type: 'error',
        duration: 5 * 1000
      })

      // TODO 401:当前用户未登录; 修改成401后 后端要加上拦截器LoginInterceptor
      if (res.code === 401) {
        // to re-login
        // MessageBox.confirm('认证失败,请登录后再访问', '提示', {
        //   confirmButtonText: '重新登录',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
          //TODO Vuex ==Vue 组件状态管理
          store.dispatch('user/resetToken').then(() => {
            //刷新
            // location.reload()
            //重定向
            Vue.prototype.$router.push({path:'/login'})
          })
        // })
      }
      return Promise.reject(new Error(res.msg || DEFAULT_ERROR_MES))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg||error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
